<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false" draggable
    :width="width >= 600 ? 600 : '100%'" @before-ok="save" @close="reset">
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns">
      <!-- 文件上传后，点击预览在新标签页打开 -->
      <template v-for="item in columns" v-slot:[item.field]="{ disabled }">
        <div v-if="item.type === 'upload' && form[item.field]">
          <!-- <a-button @click="handleClickFile(item)"> -->
            <a :href="form[item.field]" target="_blank" rel="noopener noreferrer">预览123</a>
        </div>
      </template>
    </GiForm>
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { useResetReactive } from '@/hooks'
import { addInfo, getInfo, updateInfo } from '@/apis/task/info'
import { type Columns, GiForm, type Options } from '@/components/GiForm'

// 文件处理
import { type FileItem, type FileQuery, deleteFile, listFile, uploadFile } from '@/apis'
import type { ExcelConfig } from '@/components/FilePreview/type'
import { OfficeTypes } from '@/constant/file'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改文件上传' : '新增文件上传'))
const formRef = ref<InstanceType<typeof GiForm>>()

const options: Options = {
  form: { size: 'large' },
  btns: { hide: true },
}

// 方法定义
const getFileName = (url: string): string => {
  return url.split('/').pop() || '未知文件'
}

const [form, resetForm] = useResetReactive({
})

// 示例响应结果：
// {
//     "code": "0",
//     "msg": "ok",
//     "success": true,
//     "timestamp": 1747926945038,
//     "data": {
//         "url": "http://localhost:8000/file/2025/5/22/682f3fa0b4dfcd05c5166870.pdf"
//     }
// }
const columns: Columns = reactive([
  {
    label: '文件主题',
    field: 'fileTopic',
    type: 'input',
    rules: [{ required: true, message: '请输入文件主题' }]
  },
  {
    label: '试验测试方案',
    field: 'testPlanFile',
    type: 'upload',
    props: {
      accept: '.doc,.docx,.pdf',
      multiple: false,
      action: '/api/common/file',
    },
    rules: [{ required: false, message: '请上传试验测试方案' }]
  },
  {
    label: '脉动压力传感器安装确认单',
    field: 'sensorConfirmFile',
    type: 'upload',
    props: {
      accept: '.doc,.docx,.pdf',
      multiple: false,
      action: '/api/common/file',
    }, 
    rules: [{ required: false, message: '请上传脉动压力传感器安装确认单' }]
  },
  {
    label: '传感器安装确认表',
    field: 'sensorInstallFile',
    type: 'upload',
    props: {
      accept: '.doc,.docx,.pdf',
      multiple: false,
      action: '/api/common/file',
    },
    rules: [{ required: false, message: '请上传传感器安装确认表' }]
  },
  {
    label: '试验准备变更记录表',
    field: 'trialChangeFile',
    type: 'upload',
    props: {
      accept: '.doc,.docx,.pdf',
      multiple: false,
      action: '/api/common/file',
    },
    rules: [{ required: false, message: '请上传试验准备变更记录表' }]
  },
  {
    label: '现场试验原始记录',
    field: 'fieldTestFile',
    type: 'upload',
    props: {
      accept: '.doc,.docx,.pdf',
      multiple: false,
      action: '/api/common/file',
    },
    rules: [{ required: false, message: '请上传现场试验原始记录' }]
  },
])

// 重置
const reset = async () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

// 点击文件预览
const filePreviewRef = ref()

const handleClickFile = (item: FileItem) => {
  if (OfficeTypes.includes(item.extension)) {
    const excelConfig: ExcelConfig = {
      xls: item.extension === 'xls',
      minColLength: 0,
      minRowLength: 0,
      widthOffset: 10,
      heightOffset: 10,
      beforeTransformData: (workbookData) => {
        return workbookData
      },
      transformData: (workbookData) => {
        return workbookData
      },
    }
    filePreviewRef.value.onPreview({
      fileInfo: { data: item.url, fileName: item.name, fileType: item.extension },
      excelConfig,
    })
  }
}

// 保存
const save = async () => {
  debugger
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateInfo(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addInfo(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 新增
const onAdd = async () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  debugger
  reset()
  dataId.value = id
  const { data } = await getInfo(id)
  Object.assign(form, data)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>
